//
//  SearchResultsDownload.m
//  Alfresco
//
//  Created by Michael Muller on 10/23/09.
//  Copyright 2009 Michael J Muller. All rights reserved.
//

#import "SearchResultsDownload.h"
#import "SearchResult.h"
#import "Utility.h"

#define kMaxSearchResults 30

@implementation SearchResultsDownload

@synthesize results;
@synthesize elementBeingParsed;

- (void) dealloc {
	[results release];
	[elementBeingParsed release];
	[super dealloc];
}

- (SearchResultsDownload *) initWithSearchPattern:(NSString *)pattern delegate: (id <AsynchronousDownloadDelegate>) del {
	NSString *h = userPrefHostname();
	NSString *p = userPrefPort();
	NSString *w = userPrefWebApp();
	NSString *protocol = userPrefProtocol();
	
	NSString *patternEncoded = [pattern stringByAddingPercentEscapesUsingEncoding:NSASCIIStringEncoding];
	
	NSString *urlStr = [[NSString alloc] initWithFormat:@"%@://%@:%@%@/service/search/keyword.atom?q=%@&p=1&c=%d", protocol, h, p, w, patternEncoded, kMaxSearchResults];
	NSURL *u = [NSURL URLWithString:urlStr];
	[urlStr release];
	return (SearchResultsDownload *) [self initWithURL:u delegate:del];
}

- (void)connectionDidFinishLoading:(NSURLConnection *)connection {
	
	// create an array to hold the folder items
	NSMutableArray *r = [[NSMutableArray alloc] init];
	self.results = r;
	[r release];
	
	// create a parser and parse the xml
	NSXMLParser *parser = [[NSXMLParser alloc] initWithData:self.data];
	[parser setDelegate:self];
	[parser parse];
	[parser release];

	// if the user has selected the preference to hide "dot" files, then filter those from the list
	if (!userPrefShowHiddenFiles()) {
		for (int i = [self.results count] - 1; i >= 0; i--) {
			SearchResult *item = [self.results objectAtIndex:i];
			if ([item.title hasPrefix:@"."]) {
				[self.results removeObjectAtIndex:i];
			}
		}
	}
	
	[super connectionDidFinishLoading:connection];
}

- (void)parser:(NSXMLParser *)parser didStartElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName attributes:(NSDictionary *)attributeDict {
	
	// if this is a new entry, create a repository item and add it to the list
	if ([elementName isEqualToString:@"entry"]) {
		SearchResult *r = [[SearchResult alloc] init];
		[self.results addObject:r];
		[r release];
	}
	
	if ([elementName isEqualToString:@"link"]) {
		[[self.results lastObject] setContentLocation: [attributeDict objectForKey:@"href"]];
	}
	
	self.elementBeingParsed = elementName;
}

- (void)parser:(NSXMLParser *)parser didEndElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName {
	self.elementBeingParsed = nil;
}

- (void)parser:(NSXMLParser *)parser foundCharacters:(NSString *)string {
	SearchResult *currentItem = [self.results lastObject];
	
	if ([self.elementBeingParsed isEqualToString:@"title"]) {
		currentItem.title = currentItem.title ? [currentItem.title stringByAppendingString:string] : string;
	}
	else if ([self.elementBeingParsed isEqualToString:@"relevance:score"]) {
		currentItem.relevance = currentItem.relevance ? [currentItem.relevance stringByAppendingString:string] : string;
	}
}

@end

/*
 
 sample search response
 
 $ curl "http://cm.ziaconsulting.com/alfresco/service/search/keyword.atom?q=muller&p=1&c=10&alf_ticket=TICKET_31a20990ab70be90ad4fb15d34e8f6cf0c08a7b4"
 <?xml version="1.0" encoding="UTF-8"?>
 <feed xmlns="http://www.w3.org/2005/Atom" xmlns:opensearch="http://a9.com/-/spec/opensearch/1.1/" xmlns:relevance="http://a9.com/-/opensearch/extensions/relevance/1.0/" xmlns:alf="http://www.alfresco.org/opensearch/1.0/">
 <generator version="3.2.0 (2039)">Alfresco (Community)</generator>
 <title>Alfresco Keyword Search: muller</title> 
 <updated>2009-10-03T04:12:52.441Z</updated>
 <icon>http://cm.ziaconsulting.com:80/alfresco/images/logo/AlfrescoLogo16.ico</icon>
 <author> 
 <name>mmuller</name>
 </author> 
 <id>urn:uuid:dbcc2489-7143-4c30-a481-4e574dac4e89</id>
 <opensearch:totalResults>5</opensearch:totalResults>
 <opensearch:startIndex>1</opensearch:startIndex>
 <opensearch:itemsPerPage>10</opensearch:itemsPerPage>
 <opensearch:Query role="request" searchTerms="muller" startPage="1" count="10" language="en-US"/>
 <link rel="alternate" href="http://cm.ziaconsulting.com:80/alfresco/service/search/keyword.atom?q=muller&amp;p=1&amp;c=10&amp;l=en-US&amp;guest=" type="text/html"/>
 <link rel="self" href="http://cm.ziaconsulting.com:80/alfresco/service/search/keyword.atom?q=muller&amp;p=1&amp;c=10&amp;l=en-US&amp;guest=" type="application/atom+xml"/>
 <link rel="search" type="application/opensearchdescription+xml" href="http://cm.ziaconsulting.com:80/alfresco/service/api/search/keyword/description.xml"/>
 <entry>
 <title>WBS-django-conversion.xls</title>
 <link rel="alternate" href="http://cm.ziaconsulting.com:80/alfresco/service/api/node/content/workspace/SpacesStore/986b162e-0867-4a7b-9f4f-0e3837cdc97b/WBS-django-conversion.xls"/>
 <icon>http://cm.ziaconsulting.com:80/alfresco/images/filetypes/xls.gif</icon>       
 <id>urn:uuid:986b162e-0867-4a7b-9f4f-0e3837cdc97b</id>
 <alf:noderef>workspace://SpacesStore/986b162e-0867-4a7b-9f4f-0e3837cdc97b</alf:noderef>
 <updated>2009-06-15T22:06:23.037Z</updated>
 <summary></summary>
 <author> 
 <name>mmahon</name>
 </author> 
 <relevance:score>0.012</relevance:score>
 </entry>
 
 */
